<template>
  <m-layout>
    <mt-header slot="header" :title="headerText">
      <m-header-back slot="left"/>
    </mt-header>
    <div slot="body">
      <m-section class="score">
        <m-flexbox class="score-header" justify="space-between">
          <e-heading>{{query.testMethodName}}</e-heading>
          <router-link class="blue"
                       :to="{path: '/smartCourse/historyScores',
                       query:{
                         studentId: query.studentId,
                         levelId: query.curAge,
                         testModeId: query.testModeId,
                         testMethodId: query.testMethodId,
                         testItemText: query.testItemText,
                         testMethodName: query.testMethodName,
                         ageGroupText: query.ageGroupText,
                       }}">
            查看历史成绩
          </router-link>
        </m-flexbox>
        <div class="echarts">
          <m-flexbox class="small weak" justify="space-around" align="center">
            <div class="point first">学员当日成绩</div>
            <div class="point sec">区间最好成绩</div>
            <div class="point third">所有学员当日平均成绩</div>
          </m-flexbox>
          <div ref="echartsLine"></div>
        </div>
      </m-section>
      <!--非主观题-->
      <m-section class="explain" v-if="firstScoreSimple.testScoreType===1">
        {{scoreLineEcharts.testScoreType}}
        <m-flexbox class="explain-item" justify="space-between">
          <span>最好成绩</span>
          <span class="weak">{{studentStestScoreSummary.bestScore}}{{firstScoreSimple.testScoreDesc}}</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>最好成绩比最差成绩提高了</span>
          <span class="weak">{{studentStestScoreSummary.bestWorstScoreDiff}}{{firstScoreSimple.testScoreDesc}}</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>最近一次成绩与最好成绩相比</span>
          <span class="weak">{{studentStestScoreSummary.firstBestScoreDiff}}{{firstScoreSimple.testScoreDesc}}</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>最近一次成绩与所有学员平均值相比</span>
          <span class="weak">{{studentStestScoreSummary.firstAllAvgScoreDiff}}{{firstScoreSimple.testScoreDesc}}</span>
        </m-flexbox>
      </m-section>
      <!--主观题-->
      <m-section class="explain" v-else>
        {{scoreLineEcharts.testScoreType}}
        <m-flexbox class="explain-item" justify="space-between">
          <span>获取卓越(A+)的次数</span>
          <span class="weak">{{studentStestScoreSummary.bestScore}}次</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>获取精良(A)的次数</span>
          <span class="weak">{{studentStestScoreSummary.bestWorstScoreDiff}}次</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>获取良好(B)的次数</span>
          <span class="weak">{{studentStestScoreSummary.firstBestScoreDiff}}次</span>
        </m-flexbox>
        <m-flexbox class="explain-item" justify="space-between">
          <span>获取良好(C)的次数</span>
          <span class="weak">{{studentStestScoreSummary.firstAllAvgScoreDiff}}次</span>
        </m-flexbox>
      </m-section>
    </div>
  </m-layout>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState({
      standard: state => state.smartCourse.standard,
      scoreLineEcharts: state => state.smartCourse.scoreLineEcharts
    })
  },
  data () {
    return {
      query: this.$route.query,
      headerText: `${this.$route.query.testItemText}测试成绩(${this.$route.query.ageGroupText})`,
      firstScoreSimple: {},
      studentStestScoreSummary: {},
      eCharts: {}
    }
  },
  mounted () {
    this.eChartsPromise()
  },
  methods: {
    eChartsPromise () {
      const standardReq = this.standardReq()
      const scoreLine = this.studentTestScoreLineChart()
      Promise.all([standardReq, scoreLine]).then(() => {
        this.firstScoreSimple = this.scoreLineEcharts.currentDayScores[0]
        this.studentStestScoreSummary = this.scoreLineEcharts.studentStestScoreSummary
        require.ensure([], (require) => {
          this.$$echarts = require('echarts/lib/echarts')
          require('echarts/lib/chart/line')
          // require('echarts/lib/component/markLine')
          require('echarts/lib/component/markPoint')
          this.displayECharts()
        })
      })
    },
    standardReq () {
      return this.$store.dispatch('smartCourse/standard', {
        itemId: this.query.testMethodId,
        ageId: this.query.curAge
      })
    },
    studentTestScoreLineChart () {
      return this.$store.dispatch('smartCourse/studentTestScoreLineChart', {
        levelId: this.query.curAge,
        studentId: this.query.studentId,
        testMethodId: this.query.testMethodId,
        testModeId: this.query.testModeId
      })
    },
    displayECharts () {
      const query = {
        inverse: this.scoreLineEcharts.testScoreSort, // 0：倒序，1：顺序
        testScoreType: this.firstScoreSimple.testScoreType, // 0 代表主观题，1代表非主观题
        unit: this.firstScoreSimple.testScoreType ? this.firstScoreSimple.testScoreDesc : '次', // 单位,
        standardList: this.standard.standardList, // 评分等级
        avgScores: [], // 平均成绩
        curScores: [] // 当日成绩
      }
      const avgScores = this.scoreLineEcharts.currentDayAvgScores.reverse()
      const curScores = this.scoreLineEcharts.currentDayScores.reverse()
      avgScores.forEach(avgItem => {
        query['avgScores'].push([new Date(this.timestampToTime(avgItem['testDate'])), avgItem['testScore'] + ''])
      })
      curScores.forEach(curItem => {
        query['curScores'].push([new Date(this.timestampToTime(curItem['testDate'])), curItem['testScore'] + ''])
      })
      this.$nextTick(this.showECharts(query))
    },
    timestampToTime (timestamp) {
      let date = new Date(timestamp)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = date.getDate() + ''
      return Y + M + D
    },
    showECharts (query) {
      let lineDom = this.$refs.echartsLine
      lineDom.style.height = '300px'
      this.eCharts = this.$$echarts.init(lineDom)
      this.eCharts.setOption(this.testScoreOption(query))
    },
    testScoreOption (params) {
      return {
        xAxis: { // X轴
          type: 'time',
          axisTick: {
            show: false // 刻度隐藏
          },
          axisLine: { // 线
            lineStyle: {
              color: '#e5e5e5'
            }
          },
          axisLabel: {
            color: '#999999',
            fontSize: 12,
            interval: 0
            // rotate:"45"
          },
          // splitNumber: 8,
          splitLine: {
            show: true,
            // interval: 0,
            lineStyle: {
              color: ['#FBFBFB']
            }
          }
          // data: params['testDates']
        },
        yAxis: {
          inverse: params.inverse,
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#999999',
            fontSize: 12,
            interval: 0,
            rotate: 40,
            formatter: function (value) {
              if (params.testScoreType === 1) { // 非主观题
                return value + (params.unit === '秒' ? 's' : params.unit)
              }
              for (let i = 0, j = params.standardList.length; i < j; i++) {
                let min = params.standardList[i]['minValue']
                let max = params.standardList[i]['maxValue']
                if (!min && max && value <= max) {
                  return params.standardList[i].testGrade
                }
                if (min && !max && min <= value) {
                  return params.standardList[i].testGrade
                }
                if (min && max && min <= value && value <= max) {
                  return params.standardList[i].testGrade
                }
              }
            }
          },
          axisTick: {
            show: false
          },
          // min: 0,
          // max: 300,
          splitNumber: 2, // 间隔数量
          splitLine: {
            lineStyle: {
              color: ['#e5e5e5'],
              type: 'dotted'
            }
          }
        },
        series: [
          {
            data: params['curScores'],
            showAllSymbol: true,
            markPoint: {// 最大值拐角原点
              label: {
                show: true,
                position: ['-50%', -15],
                formatter (value) {
                  let scoreValue = value['value']
                  let grade = ''
                  if (params.testScoreType === 1) { // 非主观题
                    return scoreValue + (params.unit === '秒' ? 's' : params.unit)
                  }
                  for (let i = 0, j = params.standardList.length; i < j; i++) {
                    let min = params.standardList[i]['minValue']
                    let max = params.standardList[i]['maxValue']
                    if (!min && max && scoreValue <= max) {
                      grade = params.standardList[i].testGrade
                    }
                    if (min && !max && min <= scoreValue) {
                      grade = params.standardList[i].testGrade
                    }
                    if (min && max && min <= scoreValue && scoreValue <= max) {
                      grade = params.standardList[i].testGrade
                    }
                  }
                  return grade
                }
              },
              symbol: 'circle',
              symbolSize: 6,
              itemStyle: {
                normal: {
                  color: '#D14A59'
                }
              },
              data: [
                {
                  type: params.inverse ? 'min' : 'max'
                }
              ]
            }, // end markPoint
            name: '学员当日成绩',
            type: 'line',
            smooth: true,
            itemStyle: {
              normal: {
                color: '#4192f3'
              }
            },
            lineStyle: { // 线的粗细
              normal: {
                width: 1.5,
                color: '#4192f3' // 线条颜色
              }
            },
            symbol: 'circle', // 拐角原点
            symbolSize: 6
          },
          {
            data: params['avgScores'],
            showAllSymbol: true,
            // data:[200,100,300,400,500,600,700],
            // markPoint: {
            //   data: [
            //     {type: 'max', name: '最大值'},
            //     {type: 'min', name: '最小值'}
            //   ]
            // },
            name: '所有学员当日成绩',
            type: 'line',
            boundaryGap: false,
            smooth: true,
            itemStyle: {
              normal: {
                color: '#ff8e00'
                // borderColor: "blue"  // 点边线的颜色
              }
            },
            lineStyle: { // 线的粗细
              normal: {
                width: 1.5,
                color: '#ff8e00' // 线条颜色
              }
            },
            symbol: 'circle', // 拐角原点
            symbolSize: 6
          }
        ]
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.score{
  &-header{
    padding-right: 0.3rem
  }
  .echarts{
    .small{
      position: relative;
      top: 0.5rem
    }
    .point:before{
      display: inline-block;
      content: "";
      margin-right: 0.1rem;
      width: 0.12rem;
      height: 0.12rem;
      border-radius: 100%;
    }
    .first:before{
      background: #4192f3;
    }
    .sec:before{
      background: #de4a59;
    }
    .third:before{
      background: #ff8e00
    }
  }
}
.explain{
  &-item{
    padding: 0 0.3rem;
    height: 1.1rem;
  }
}
</style>
